﻿using Markdig;

namespace zijian666.Updater.WinForm;
public partial class UpdateForm : Form
{
    private readonly WebBrowser webBrowser1;

    public UpdateForm(RemoteData.VersionInfo version)
    {
        InitializeComponent();
        VersionInfo = version;
        Text = $"发现新版本 {version.Version}";
        webBrowser1 = new WebBrowser
        {
            Dock = DockStyle.Fill
        };
        this.panView.Controls.Add(webBrowser1);
        DisableUpdate();
        _ = LoadChangeLog();
    }

    private void DisableUpdate()
    {
        btnUpdate.Enabled = false;
    }
    public RemoteData.VersionInfo VersionInfo { get; }

    async Task LoadChangeLog()
    {
        webBrowser1.Loading();
        string? view = null;
        if (!string.IsNullOrWhiteSpace(VersionInfo.ChangeLog))
        {
            try
            {
                view = await Helper.ReadString(VersionInfo.ChangeLog);

                // 使用 Markdig 转换为 HTML
                view = Markdown.ToHtml(view);

                // 包装成完整 HTML（可加 CSS 样式）
                view = $@"
            <html>
            <head>
                <meta charset='utf-8'>
                <style>
                    body {{ font-family: Arial; padding: 10px; }}
                    h1 {{ color: #2c3e50; }}
                </style>
            </head>
            <body>
                {view}
            </body>
            </html>";
            }
            catch (Exception ex)
            {
                view = $"<html><body><h1>加载更新日志失败</h1><pre>{ex}</pre></body></html>";
            }
        }

        webBrowser1.Run(() =>
        {
            if (view is null)
            {
                webBrowser1.Loading("暂无更新日志");
            }
            else
            {
                webBrowser1.DocumentText = view;
            }
            btnUpdate.Enabled = true;
        });
    }

}
